<?php
/*
 * session 处理函数
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 18a23b91fc81948c9c0d48e11562c88ad822d069 $
 * @time       14-1-21 下午2:58
 */
/**
 * session handler
 * Class SessionHandler
 */
class PSessionHandler {

	private $_db;
	private $_table;
	private $_lifetime;

	function __construct() {
		global $db;
		$this->_db = $db;
		$this->_table = $db->getPre().'session';
		$this->_lifetime = 1800;
	}

	function open($savePath, $sessionName) {
		return true;
	}

	function close() {
		return $this->gc($this->_lifetime);
	}

	function read($id) {
		$data = $this->_db->getVar('select data from '. $this->_db->getPre().'session where sessionid = "'.$id.'"');
		return $data ? $data : '';
	}

	function write($id, $data) {
		$ip = Env::ip();
		$time = Env::time();
		$sql = "REPLACE INTO {$this->_table} (sessionid, data, lastvisit, ip) values ('{$id}','{$data}', '{$time}', '{$ip}')";
		return $this->_db->query($sql);
	}

	function destroy($id) {
		return $this->_db->query(Sql::delete($this->_table, "sessionid='{$id}'"));
	}

	function gc($maxlifetime) {
		$expiretime = Env::time() - $maxlifetime;
		$sql = "select * from {$this->_table} where `lastvisit`<$expiretime";
		$data = $this->_db->query($sql);

		// 删除图片
		foreach($data as $k => $v) {
			if (isset($v['uploads']) && !empty($v['uploads'])) {
				foreach($v['uploads'] as $uk => $uv) {
					Picture::delete($uv['url']);
					PictureUpload::clearPictureSession(Picture::basename($uv['url']));
				}
			}
		}

		// 清理 session
		return $this->_db->query(Sql::delete($this->_table, "`lastvisit`<$expiretime"));
	}
}
